<template>
  <div class="tcm-market">
    <!-- 背景轮播图 -->
    <div class="background-carousel">
      <el-carousel 
        height="100vh" 
        :interval="6000" 
        arrow="never" 
        indicator-position="none"
        :autoplay="true"
        class="background-carousel-container"
        :initial-index="0"
      >
        <el-carousel-item v-for="(image, index) in backgroundImages" :key="index">
          <div class="carousel-image" :style="{ backgroundImage: `url(${image})` }"></div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 内容区域 -->
    <div class="content-overlay">
      <!-- 顶部导航栏 -->
      <div class="market-header">
        <div class="header-content">
          <div class="logo">
            <h1>中药进销存ProMax</h1>
            <div class="logo-decoration"></div>
          </div>
          <div class="search-bar">
            <el-input
                v-model="searchQuery"
                placeholder="搜索中药材..."
                class="search-input"
                @keyup.enter="handleSearch"
                clearable
                @clear="resetSearch"
            >
              <template #prefix>
                <el-icon class="search-icon"><Search /></el-icon>
              </template>
              <template #append>
                <el-button type="primary" @click="handleSearch" :loading="isSearching" class="search-button">
                  搜索
                </el-button>
              </template>
            </el-input>
          </div>
          <div class="user-actions">
            <el-dropdown trigger="click">
              <div class="user-info" style="display: flex;">
                <el-avatar :size="40" :src="userAvatar" />
                <span style="position: relative;margin-top: 10px;margin-left: 10px">{{ username }}</span>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goToCart">
                    <el-icon><ShoppingCart /></el-icon>
                    购物车
                  </el-dropdown-item>
                  <el-dropdown-item @click="goToDingdan">
                    <el-icon><ShoppingCart /></el-icon>
                    订单详情
                  </el-dropdown-item>
                  <el-dropdown-item @click="goToFavorites">
                    <el-icon><Star /></el-icon>
                    收藏夹
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleUploadAvatar">
                    <el-icon><Upload /></el-icon>
                    上传头像
                  </el-dropdown-item>
                  <el-dropdown-item @click="showBecomeMerchantDialog">
                    <el-icon><Shop /></el-icon>
                    成为商家
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">
                    <el-icon><SwitchButton /></el-icon>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>

      <!-- 主要内容区 -->
      <div class="market-content">
        <!-- 分类侧边栏 -->
        <div class="category-sidebar">
          <h3>药材分类</h3>
          <div class="category-decoration"></div>
          <el-skeleton :rows="3" animated v-if="loading && !categories.length" />
          <el-menu
              v-else
              :default-active="activeCategory"
              class="category-menu"
              @select="handleCategorySelect"
          >
            <el-menu-item
                v-for="category in categories"
                :key="category.id"
                :index="category.id.toString()"
            >
              <el-icon><Box /></el-icon>
              <span>{{ category.name }}</span>
            </el-menu-item>
          </el-menu>
        </div>

        <!-- 商品展示区 -->
        <div class="product-area">
          <div class="product-filters">
            <el-radio-group v-model="sortBy" @change="handleSortChange">
              <el-radio-button value="price">价格</el-radio-button>
              <el-radio-button value="sales">销量</el-radio-button>
            </el-radio-group>
          </div>

          <!-- 商品垂直滚动展示 -->
          <div class="product-scroll" v-if="products.length > 0">
            <el-scrollbar height="600px">
              <div class="scroll-content">
                <el-card
                    v-for="(product, index) in products"
                    :key="index"
                    class="product-card"
                    :body-style="{ padding: '0px' }"
                    :data-product-id="product.id"
                >
                  <div class="product-item">
                    <div class="product-image-container">
                      <img :src="product.image || '../../public/7655.jpg_wh860.jpg'" class="product-image">
                      <div class="image-overlay"></div>
                    </div>
                    <div class="product-info">
                      <h3 class="product-name">{{ product.name }}</h3>
                      <p class="product-desc">{{ product.description }}</p>
                      <div class="product-price">
                        <span class="price">¥{{ product.price }}</span>
                        <span class="sales">销量: {{ product.sales }}</span>
                      </div>
                      <div class="product-actions">
                        <div class="action-buttons">
                          <el-button
                              type="primary"
                              size="small"
                              @click="addToCart(product)"
                              class="action-btn add-to-cart-btn"
                              :loading="cartLoading"
                          >
                            <el-icon><ShoppingCart /></el-icon>
                            加入购物车
                          </el-button>
                          <el-button
                              type="warning"
                              size="small"
                              @click="toggleFavorite(product)"
                              class="action-btn favorite-btn"
                              :class="{ 'is-favorite': isFavorite(product) }"
                          >
                            <el-icon><Star /></el-icon>
                            {{ isFavorite(product) ? '取消收藏' : '收藏' }}
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-card>
              </div>
            </el-scrollbar>
          </div>

          <!-- 无搜索结果提示 -->
          <div v-else-if="searchQuery" class="no-results">
            <el-empty description="未找到相关药材" />
          </div>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[12, 24, 36, 48]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 悬浮购物车图标 -->
    <div class="floating-cart-icon" v-show="cartItems.length > 0" @click="toggleCart">
      <el-badge :value="cartItems.length" :max="99" class="cart-badge">
        <div class="cart-icon-container">
          <div class="cart-body">
            <el-icon class="cart-icon"><ShoppingCart /></el-icon>
          </div>
          <div class="cart-wheels">
            <div class="wheel left"></div>
            <div class="wheel right"></div>
          </div>
          <div class="cart-handle"></div>
        </div>
      </el-badge>
      <div class="cart-tooltip">查看购物车</div>
    </div>

    <!-- 购物车抽屉 -->
    <el-drawer
        v-model="cartVisible"
        title="购物车"
        direction="rtl"
        size="400px"
        :destroy-on-close="false"
        :modal="false"
        :with-header="true"
        class="floating-cart"
    >
      <div class="cart-content">
        <div v-if="cartItems.length === 0" class="empty-cart">
          <el-empty description="购物车是空的" />
        </div>
        <div v-else>
          <div class="cart-header">
            <el-checkbox
              v-model="selectAll"
              @change="handleSelectAllChange"
              :indeterminate="isIndeterminate"
            >
              全选
            </el-checkbox>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleBatchDelete"
              :disabled="selectedCount === 0"
            >
              删除选中
            </el-button>
          </div>
          <div class="cart-items">
            <div v-for="item in cartItems" :key="item.id" class="cart-item">
              <div class="item-info">
                <el-checkbox
                  v-model="item.selected"
                  @change="handleItemSelect"
                />
                <img :src="item.image || '../../public/1.jpg'" class="item-image">
                <div class="item-details">
                  <h4>{{ item.name }}</h4>
                  <p class="item-price">¥{{ item.price }}</p>
                </div>
              </div>
              <div class="item-actions">
                <el-input-number
                    v-model="item.quantity"
                    :min="1"
                    size="small"
                    @change="(val) => updateQuantity(item, val)"
                />
              </div>
            </div>
          </div>
          <div class="cart-footer">
            <div class="cart-total">
              <span>已选商品：{{ selectedCount }}件</span>
              <span>总计：</span>
              <span class="total-price">¥{{ selectedTotal.toFixed(2) }}</span>
            </div>
            <div class="cart-actions">
              <el-button type="danger" @click="clearCart">清空购物车</el-button>
              <el-button 
                type="primary" 
                @click="checkout"
                :disabled="selectedCount === 0"
              >
                去结算
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 收藏夹抽屉 -->
    <el-drawer
        v-model="favoritesVisible"
        title="收藏夹"
        direction="rtl"
        size="400px"
        :destroy-on-close="false"
    >
      <div class="favorites-content">
        <div v-if="favoriteItems.length === 0" class="empty-favorites">
          <el-empty description="收藏夹是空的" />
        </div>
        <div v-else>
          <div class="favorite-items">
            <div v-for="item in favoriteItems" :key="item.id" class="favorite-item">
              <div class="item-info">
                <img :src="item.image || '../../public/1.jpg'" class="item-image">
                <div class="item-details">
                  <h4>{{ item.name }}</h4>
                  <p class="item-price">¥{{ item.price }}</p>
                </div>
              </div>
              <div class="item-actions">
                <el-button
                    type="primary"
                    size="small"
                    @click="addToCart(item)"
                >
                  加入购物车
                </el-button>
                <el-button
                    type="danger"
                    size="small"
                    @click="toggleFavorite(item)"
                >
                  取消收藏
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 订单确认对话框 -->
    <el-dialog
        v-model="orderDialogVisible"
        title="订单确认"
        width="50%"
        :close-on-click-modal="false"
    >
      <div class="order-confirm-content">
        <!-- 用户信息 -->
        <div class="user-info-section">
          <h3>用户信息</h3>
          <el-form :model="orderForm" label-width="100px">
            <el-form-item label="用户名">
              <el-input v-model="username" disabled />
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="orderForm.deliveryPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-form>
        </div>

        <!-- 地址信息 -->
        <div class="address-section">
          <h3>地址信息</h3>
          <el-form :model="orderForm" label-width="100px">
            <el-form-item label="发货地址">
              <el-input v-model="orderForm.shippingAddress" disabled />
            </el-form-item>
            <el-form-item label="收货人">
              <el-input v-model="orderForm.deliveryName" placeholder="请输入收货人姓名" />
            </el-form-item>
            <el-form-item label="收货地址">
              <el-input
                v-model="orderForm.deliveryAddress"
                type="textarea"
                placeholder="请输入详细收货地址"
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 订单商品列表 -->
        <div class="order-items">
          <h3>订单商品</h3>
          <div v-for="item in selectedCartItems" :key="item.id" class="order-item">
            <el-image :src="item.image || '../../public/1.jpg'" class="item-image" />
            <div class="item-info">
              <h4>{{ item.name }}</h4>
              <p>单价: ¥{{ item.price }}</p>
              <p>数量: {{ item.quantity }}</p>
              <p>小计: ¥{{ (item.price * item.quantity).toFixed(2) }}</p>
            </div>
          </div>
        </div>

        <!-- 订单金额 -->
        <div class="order-total">
          <h3>订单金额</h3>
          <p>商品总额: ¥{{ selectedTotal.toFixed(2) }}</p>
          <p>运费: ¥{{ shippingFee.toFixed(2) }}</p>
          <p class="grand-total">实付金额: ¥{{ (selectedTotal + shippingFee).toFixed(2) }}</p>
        </div>

        <!-- 支付方式 -->
        <div class="payment-method">
          <h3>支付方式</h3>
          <el-radio-group v-model="orderForm.paymentMethod">
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="wechat">微信支付</el-radio>
          </el-radio-group>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="orderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOrder" :loading="submitting">
            提交订单
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 成为商家对话框 -->
    <el-dialog
      v-model="merchantDialogVisible"
      title="成为商家"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="merchantFormRef"
        :model="merchantForm"
        :rules="merchantFormRules"
        label-width="100px"
        v-loading="merchantFormLoading"
      >
        <el-form-item label="账号">
          <el-input v-model="merchantForm.username" disabled />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="merchantForm.name" disabled />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="merchantForm.phone" disabled />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="merchantForm.email" disabled />
        </el-form-item>
        <el-form-item label="当前角色">
          <el-select v-model="merchantForm.role" placeholder="请选择角色">
            <el-option label="客户" value="customer" />
            <el-option label="商家" value="merchant" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请理由" prop="reason">
          <el-input
              v-model="merchantForm.applyReason"
              type="textarea"
              placeholder="请说明申请成为商家的理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="merchantDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitMerchantForm" :loading="merchantFormSubmitting">
            申请
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, ShoppingCart, List, Box, Upload, SwitchButton, Shop, Star, Delete } from '@element-plus/icons-vue'
import request from '@/utils/request.js'
import { useRouter } from 'vue-router'
import { useCartStore } from '@/store/modules/cart'

const router = useRouter()
const username = ref('')
const userAvatar = ref('')

// 搜索框相关
const searchQuery = ref('')
const searchResults = ref([])
const isSearching = ref(false)
const highlightedProduct = ref(null)

// 商品列表相关
const products = ref([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const sortBy = ref('price')

// 分类相关
const categories = ref([])
const activeCategory = ref('')
const loading = ref(false)

// 购物车相关
const cartStore = useCartStore()
const cartVisible = ref(false)
const cartLoading = ref(false)

// 成为商家相关
const merchantDialogVisible = ref(false)
const merchantFormRef = ref(null)
const merchantFormLoading = ref(false)
const merchantFormSubmitting = ref(false)
const merchantForm = ref({
  id: '',
  name: '',
  username: '',
  password: '',
  role: '',
  phone: '',
  email: '',
  status: 1,
  applyReason:''
})

const merchantFormRules = {
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}
//订单详情
function goToDingdan() {
  router.push('/DingDan');
}

// 收藏夹相关
const favoritesVisible = ref(false)
const favoriteItems = ref([])

// 背景轮播图数据
const backgroundImages = [
  '/1.jpg',
  '/2.jpg',
  '/3.jpg',
  '/3.jfif'
]

// 获取分类数据
const getCategories = async () => {
  try {
    loading.value = true
    console.log('开始获取分类数据...')
    const res = await request.get('category/findAllCategory')  // 更新为正确的API路径
    console.log('分类数据响应:', res)

    if (!res) {
      throw new Error('未收到响应数据')
    }

    if (res.code === 200) {
      if (Array.isArray(res.data.data)) {  // 更新为正确的数据结构
        categories.value = res.data.data
        if (categories.value.length > 0) {
          activeCategory.value = categories.value[0].id.toString()
          await loadProductsByCategory(activeCategory.value)
        } else {
          ElMessage.warning('暂无分类数据')
        }
      } else {
        throw new Error('分类数据格式错误: ' + JSON.stringify(res.data))
      }
    } else {
      throw new Error(res.message || '获取分类失败，错误码: ' + res.code)
    }
  } catch (error: any) {
    console.error('获取分类失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response,
      status: error.status
    })
    ElMessage.error(error.message || '获取分类失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 根据分类加载商品
const loadProductsByCategory = async (categoryId: string) => {
  console.log("categoryId",categoryId)
  if (!categoryId) {
    console.warn('分类ID为空')
    return
  }

  try {
    loading.value = true
    console.log('开始获取商品数据，分类ID:', categoryId)
    // 根据分类ID获取分类名称
    const category = categories.value.find(c => c.id.toString() === categoryId)
    if (!category) {
      throw new Error('未找到对应的分类')
    }

    const res = await request.get(`medicine/findAllMedicine`, {
      params: {
        category: category.name,  // 使用分类名称而不是ID
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    })
    console.log('商品数据响应:', res)

    if (!res) {
      throw new Error('未收到响应数据')
    }

    if (res.code === 200) {
      if (Array.isArray(res.data.content)) {
        products.value = res.data.content.map(medicine => ({
          ...medicine,
          price: medicine.sale_price,  // 使用销售价格
          sales: medicine.store_count  // 使用库存数量作为销量
        }))
        total.value = res.data.totalElements
        
        // 根据当前排序方式对商品进行排序
        if (sortBy.value === 'price') {
          products.value.sort((a, b) => a.price - b.price)
        } else if (sortBy.value === 'sales') {
          products.value.sort((a, b) => b.sales - a.sales)
        }
      } else {
        throw new Error('商品数据格式错误: ' + JSON.stringify(res.data))
      }
    } else {
      throw new Error(res.message || '获取商品失败，错误码: ' + res.code)
    }
  } catch (error: any) {
    console.error('获取商品失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response,
      status: error.status
    })
    ElMessage.error(error.message || '获取商品失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理分类选择
const handleCategorySelect = async (index: string) => {
  console.log('选择分类:', index)
  if (!index) {
    console.warn('无效的分类ID')
    return
  }
  activeCategory.value = index
  await loadProductsByCategory(index)
}

// 处理搜索
const handleSearch = async () => {
  if (!searchQuery.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  try {
    isSearching.value = true
    const res = await request.get('medicine/findAllMedicine', {
      params: {
        name: searchQuery.value,
        pageNum: 1,
        pageSize: 100 // 获取更多结果以便搜索
      }
    })

    if (res.code === 200 && Array.isArray(res.data.content)) {
      searchResults.value = res.data.content.map(medicine => ({
        ...medicine,
        price: medicine.sale_price,
        sales: medicine.store_count
      }))

      if (searchResults.value.length > 0) {
        // 更新商品列表
        products.value = searchResults.value
        total.value = searchResults.value.length

        // 根据当前排序方式对搜索结果进行排序
        if (sortBy.value === 'price') {
          products.value.sort((a, b) => a.price - b.price)
        } else if (sortBy.value === 'sales') {
          products.value.sort((a, b) => b.sales - a.sales)
        }

        // 高亮显示第一个匹配项
        highlightedProduct.value = searchResults.value[0].id
        await nextTick()
        scrollToProduct(highlightedProduct.value)
      } else {
        ElMessage.info('未找到相关药材')
      }
    } else {
      throw new Error(res.message || '搜索失败')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请稍后重试')
  } finally {
    isSearching.value = false
  }
}

// 滚动到指定商品
const scrollToProduct = (productId) => {
  const productElement = document.querySelector(`[data-product-id="${productId}"]`)
  if (productElement) {
    productElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
    // 添加高亮效果
    productElement.classList.add('highlight-product')
    setTimeout(() => {
      productElement.classList.remove('highlight-product')
    }, 2000)
  }
}

// 重置搜索
const resetSearch = () => {
  searchQuery.value = ''
  searchResults.value = []
  highlightedProduct.value = null
  if (activeCategory.value) {
    loadProductsByCategory(activeCategory.value)
  }
}

// 处理排序变化
const handleSortChange = (value: string) => {
  console.log('Sort by:', value)
  if (!products.value || products.value.length === 0) return
  
  // 根据选择的排序方式对商品进行排序
  if (value === 'price') {
    // 按价格排序（从低到高）
    products.value.sort((a, b) => a.price - b.price)
  } else if (value === 'sales') {
    // 按销量排序（从高到低）
    products.value.sort((a, b) => b.sales - a.sales)
  }
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  // 重新加载数据
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  // 重新加载数据
}

// 切换购物车显示状态
const toggleCart = () => {
  cartVisible.value = !cartVisible.value
}

// 添加商品到购物车
const addToCart = async (product) => {
  try {
    cartLoading.value = true
    const user_name = sessionStorage.getItem('user-name')
    if (!user_name) {
      ElMessage.warning('请先登录')
      return
    }

    const cartItem = {
      user_name: user_name,
      medicine_id: product.id,
      quantity: 1
    }

    const res = await request.post('/shop/addShop', cartItem)
    if (res.code === 200) {
      cartStore.addItem({...product, selected: false})
      // 显示添加成功的动画效果
      showAddToCartAnimation(product)
      ElMessage.success('已添加到购物车')
    } else {
      ElMessage.error(res.message || '添加失败')
    }
  } catch (error) {
    console.error('添加购物车失败:', error)
    ElMessage.error('添加失败，请稍后重试')
  } finally {
    cartLoading.value = false
  }
}

// 添加购物车动画效果
const showAddToCartAnimation = (product) => {
  const cartIcon = document.querySelector('.floating-cart-icon')
  if (!cartIcon) return

  const productElement = document.querySelector(`[data-product-id="${product.id}"]`)
  if (!productElement) return

  const productRect = productElement.getBoundingClientRect()
  const cartRect = cartIcon.getBoundingClientRect()

  const animation = document.createElement('div')
  animation.className = 'add-to-cart-animation'
  animation.style.cssText = `
    position: fixed;
    top: ${productRect.top}px;
    left: ${productRect.left}px;
    width: 30px;
    height: 30px;
    background: #409EFF;
    border-radius: 50%;
    z-index: 9999;
    pointer-events: none;
  `

  document.body.appendChild(animation)

  requestAnimationFrame(() => {
    animation.style.transition = 'all 0.8s cubic-bezier(0.2, 0.5, 0.3, 1)'
    animation.style.transform = `translate(${cartRect.left - productRect.left}px, ${cartRect.top - productRect.top}px) scale(0.1)`
    animation.style.opacity = '0'
  })

  setTimeout(() => {
    document.body.removeChild(animation)
  }, 800)
}

// 更新商品数量
const updateQuantity = (item, quantity) => {
  // 只更新本地状态
  cartStore.updateQuantity(item.id, quantity)
  // 更新本地购物车数据
  const index = cartItems.value.findIndex(cartItem => cartItem.id === item.id)
  if (index !== -1) {
    cartItems.value[index].quantity = quantity
  }
}

// 从购物车移除商品
const removeFromCart = async (item) => {
  try {
    const res = await request.delete(`/shop/deleteShopCar/${item.id}`)
    if (res.code === 200) {
      cartStore.removeItem(item.id)
      ElMessage.success('已从购物车移除')
    } else {
      ElMessage.error(res.message || '移除失败')
    }
  } catch (error) {
    console.error('移除商品失败:', error)
    ElMessage.error('移除失败，请稍后重试')
  }
}

// 清空购物车
const clearCart = async () => {
  try {
    const res = await request.delete('/shop/deleteBatchOrder', {
      data: cartStore.items.map(item => item.id)
    })
    if (res.code === 200) {
      cartStore.clearCart()
      ElMessage.success('购物车已清空')
    } else {
      ElMessage.error(res.message || '清空失败')
    }
  } catch (error) {
    console.error('清空购物车失败:', error)
    ElMessage.error('清空失败，请稍后重试')
  }
}

// 计算购物车总价
const cartTotal = computed(() => {
  return cartStore.cartTotal
})

// 获取购物车商品列表
const cartItems = computed(() => {
  return cartStore.items
})

// 跳转到购物车页面
const goToCart = () => {
  cartVisible.value = true
}

// 结算
const checkout = async () => {
  const selectedItems = cartItems.value.filter(item => item.selected)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }

  // 关闭购物车抽屉
  cartVisible.value = false

  // 打开订单确认对话框
  orderDialogVisible.value = true
}

// 订单表单数据
const orderForm = ref({
  deliveryName: '',
  deliveryPhone: '',
  deliveryAddress: '',
  shippingAddress: '四川省眉山市彭山区锦江大道1号',  // 设置默认发货地址
  paymentMethod: 'alipay'
})

// 订单对话框显示状态
const orderDialogVisible = ref(false)
const submitting = ref(false)

// 运费
const shippingFee = ref(10)

// 计算总金额
const totalAmount = computed(() => {
  return cartItems.value
    .filter(item => item.selected)
    .reduce((total, item) => {
      return total + (item.price * item.quantity)
    }, 0)
})

// 获取用户信息
const getUserInfo = () => {
  const storedUsername = sessionStorage.getItem('user-name')
  if (storedUsername) {
    username.value = JSON.parse(storedUsername)
  }
  // 从localStorage获取头像
  const storedAvatar = localStorage.getItem('user_avatar')
  if (storedAvatar) {
    userAvatar.value = storedAvatar
  } else {
    // 默认头像
    userAvatar.value = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
  }
}

// 处理上传头像
const handleUploadAvatar = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.onchange = (e: any) => {
    const file = e.target.files[0]
    if (file) {
      // 创建文件阅读器
      const reader = new FileReader()
      reader.onload = (e: any) => {
        // 保存到localStorage
        localStorage.setItem('user_avatar', e.target.result)
        userAvatar.value = e.target.result
        ElMessage.success('头像上传成功')
      }
      reader.readAsDataURL(file)
    }
  }
  input.click()
}

// 处理退出登录
const handleLogout = () => {
  // 清除用户信息
  localStorage.removeItem('root_token')
  localStorage.removeItem('user_role')
  localStorage.removeItem('user_avatar')
  sessionStorage.removeItem('user-name')

  ElMessage.success('退出成功')
  router.push('/login')
}

// 显示成为商家对话框
const showBecomeMerchantDialog = async () => {
  merchantDialogVisible.value = true
  await fetchUserInfo()
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    merchantFormLoading.value = true
    const user_name = JSON.parse(sessionStorage.getItem('user-name'))
    console.log(user_name)
    if (!user_name) {
      ElMessage.error('未获取到用户信息，请重新登录')
      return
    }

    const res = await request.get(`/user/finduserByName/${user_name}`)
    console.log("用户",res)

    if (res && res.code === 200) {
      // 更新表单数据
      merchantForm.value = {
        id: res.data.id,
        name: res.data.name,
        username: res.data.username,
        password: res.data.password,
        role: res.data.role,
        phone: res.data.phone,
        email: res.data.email,
        status: res.data.status,
        applyReason: '' // 添加这个字段
      }
    } else {
      throw new Error(res?.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败，请稍后重试')
  } finally {
    merchantFormLoading.value = false
  }
}

// 提交商家申请表单
const submitMerchantForm = async () => {
  if (!merchantFormRef.value) return

  try {
    // 验证表单
    await merchantFormRef.value.validate()
    merchantFormSubmitting.value = true

    // 准备申请数据
    const applicationData = {
      userId:merchantForm.value.id,
      oldRole: merchantForm.value.role,    // 当前角色（从表单获取）
      newRole: 'merchant',                 // 固定申请成为商家
      applyDate: new Date(),               // 申请日期（当前时间）
      status: '待处理',                   // 初始状态设为"待处理"
      reason: merchantForm.value.applyReason        // 申请理由
    }

    console.log("表单信息",applicationData)
    console.log("申请理由",merchantForm.value.applyReason)
    // 发送申请请求
    const res = await request.post('/apply/addApply', applicationData)
    console.log(res)

    if (res && res.code === 200) {
      ElMessage.success('商家申请已提交，请等待管理员审核')
      merchantDialogVisible.value = false
    } else {
      throw new Error(res?.message || '提交申请失败')
    }
  } catch (error) {
    console.error('提交申请失败:', error)
    ElMessage.error(error.message || '提交申请失败，请稍后重试')
  } finally {
    merchantFormSubmitting.value = false
  }
}

// 检查商品是否已收藏
const isFavorite = (product) => {
  return favoriteItems.value.some(item => item.id === product.id)
}

// 切换收藏状态
const toggleFavorite = (product) => {
  const index = favoriteItems.value.findIndex(item => item.id === product.id)
  if (index === -1) {
    favoriteItems.value.push(product)
    ElMessage.success('已添加到收藏夹')
  } else {
    favoriteItems.value.splice(index, 1)
    ElMessage.success('已从收藏夹移除')
  }
  // 保存到本地存储
  localStorage.setItem('favorite_items', JSON.stringify(favoriteItems.value))
}

// 打开收藏夹
const goToFavorites = () => {
  favoritesVisible.value = true
}

// 在 script setup 部分添加以下代码
const selectAll = ref(false)
const isIndeterminate = ref(false)

// 计算选中的商品数量
const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.selected).length
})

// 计算选中商品的总价
const selectedTotal = computed(() => {
  return cartItems.value
    .filter(item => item.selected)
    .reduce((total, item) => total + (item.price * item.quantity), 0)
})

// 处理全选变化
const handleSelectAllChange = (val) => {
  cartItems.value.forEach(item => {
    item.selected = val
  })
  isIndeterminate.value = false
}

// 处理单个商品选择变化
const handleItemSelect = () => {
  const selectedCount = cartItems.value.filter(item => item.selected).length
  const totalCount = cartItems.value.length
  
  selectAll.value = selectedCount === totalCount
  isIndeterminate.value = selectedCount > 0 && selectedCount < totalCount
}

// 计算选中的购物车商品
const selectedCartItems = computed(() => {
  return cartItems.value.filter(item => item.selected)
})

// 提交订单
const submitOrder = async () => {
  // 表单验证
  if (!orderForm.value.deliveryName) {
    ElMessage.warning('请输入收货人姓名')
    return
  }
  if (!orderForm.value.deliveryPhone) {
    ElMessage.warning('请输入联系电话')
    return
  }
  if (!orderForm.value.deliveryAddress) {
    ElMessage.warning('请输入详细地址')
    return
  }

  submitting.value = true
  try {
    // 构建订单数据
    const orderData = {
      userName: JSON.parse(sessionStorage.getItem('user-name')),
      shippingAddress: orderForm.value.shippingAddress,
      deliveryName: orderForm.value.deliveryName,
      deliveryPhone: orderForm.value.deliveryPhone,
      deliveryAddress: orderForm.value.deliveryAddress,
      paymentMethod: orderForm.value.paymentMethod,
      totalAmount: selectedTotal.value + shippingFee.value,
      orderStatus: 0, // 0: 未支付
      items: selectedCartItems.value.map(item => ({
        medicineId: item.id,
        medicineName: item.name,
        quantity: item.quantity,
        price: item.price,
        subtotal: item.price * item.quantity
      }))
    }

    // 发送订单数据到后端
    const response = await request.post('/api/orders', orderData)
    console.log("订单响应信息", response)
    
    if (response.code) {
      ElMessage.success('订单提交成功')
      // 清空已选中的商品
      const selectedIds = selectedCartItems.value.map(item => item.id)
      await clearSelectedItems(selectedIds)
      // 关闭订单对话框
      orderDialogVisible.value = false
      // 重置表单
      orderForm.value = {
        deliveryName: '',
        deliveryPhone: '',
        deliveryAddress: '',
        shippingAddress: '四川省眉山市彭山区锦江大道1号',
        paymentMethod: 'alipay'
      }
    } else {
      throw new Error('订单提交失败')
    }
  } catch (error) {
    console.error('提交订单失败:', error)
    ElMessage.error('提交订单失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 清空已选中的商品
const clearSelectedItems = async (selectedIds) => {
  try {
    const res = await request.delete('/shop/deleteBatchOrder', {
      data: selectedIds
    })
    if (res.code === 200) {
      // 从购物车中移除已选中的商品
      selectedIds.forEach(id => {
        cartStore.removeItem(id)
      })
    } else {
      throw new Error(res.message || '清空选中商品失败')
    }
  } catch (error) {
    console.error('清空选中商品失败:', error)
    ElMessage.error('清空选中商品失败，请稍后重试')
  }
}

// 处理单个商品删除
const handleDeleteItem = async (item) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个商品吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await request.delete(`/shop/deleteShopCar/${item.id}`)
    if (res.code === 200) {
      cartStore.removeItem(item.id)
      ElMessage.success('商品已删除')
    } else {
      throw new Error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 处理批量删除
const handleBatchDelete = async () => {
  const selectedItems = cartItems.value.filter(item => item.selected)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要删除的商品')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedItems.length} 个商品吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const selectedIds = selectedItems.map(item => item.id)
    const res = await request.delete('/shop/deleteBatchOrder', {
      data: selectedIds
    })
    
    if (res.code === 200) {
      selectedIds.forEach(id => {
        cartStore.removeItem(id)
      })
      ElMessage.success('商品已删除')
    } else {
      throw new Error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

onMounted(async () => {
  await getUserInfo()
  await getCategories()
  cartVisible.value = false // 确保购物车初始状态为隐藏
  // 从本地存储加载收藏数据
  const savedFavorites = localStorage.getItem('favorite_items')
  if (savedFavorites) {
    favoriteItems.value = JSON.parse(savedFavorites)
  }
})
</script>

<style scoped>
.tcm-market {
  position: relative;
  min-height: 100vh;
  overflow: hidden;
  background: #f8f9fa;
}

.background-carousel {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  overflow: hidden;
}

.background-carousel-container {
  width: 100%;
  height: 100%;
}

.carousel-image {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  transform: scale(1.05);
  transition: transform 8s ease-in-out;
}

.content-overlay {
  position: relative;
  z-index: 1;
  background: rgba(255, 255, 255, 0.95);
  min-height: 100vh;
}

.market-header {
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  padding: 20px 0;
  position: relative;
  z-index: 10;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
}

.logo h1 {
  color: #2c3e50;
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: 1px;
}

.logo-decoration {
  position: absolute;
  top: -10px;
  right: -10px;
  width: 30px;
  height: 30px;
  background: linear-gradient(45deg, #00f2fe, #4facfe);
  border-radius: 50%;
  opacity: 0.8;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 0.8;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.5;
  }
  100% {
    transform: scale(1);
    opacity: 0.8;
  }
}

.search-bar {
  flex: 1;
  max-width: 500px;
  margin: 0 40px;
  position: relative;
}

.search-input {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.search-input:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.search-input:focus-within {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.search-input :deep(.el-input__wrapper) {
  box-shadow: none;
  border-radius: 8px;
  padding-right: 100px;
  background: #fff;
  border: 1px solid #eaeaea;
}

.search-input :deep(.el-input__inner) {
  height: 44px;
  font-size: 15px;
  padding-left: 40px;
  color: #2c3e50;
}

.search-input :deep(.el-input__prefix) {
  left: 12px;
}

.search-input :deep(.el-input-group__append) {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  background: transparent;
  border: none;
  padding: 0;
}

.search-input :deep(.el-input-group__append button) {
  height: 100%;
  border-radius: 0 8px 8px 0;
  padding: 0 24px;
  font-size: 15px;
  font-weight: 500;
  background: #2c3e50;
  border: none;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input-group__append button:hover) {
  background: #34495e;
}

.market-content {
  max-width: 1200px;
  margin: 40px auto;
  display: flex;
  gap: 30px;
  position: relative;
  z-index: 1;
  padding: 0 24px;
}

.category-sidebar {
  width: 240px;
  background: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.category-sidebar h3 {
  color: #2c3e50;
  margin: 0 0 20px 0;
  padding: 0 0 16px 0;
  border-bottom: 1px solid #eaeaea;
  font-size: 18px;
  font-weight: 600;
}

.product-area {
  flex: 1;
  background: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.product-filters {
  margin-bottom: 24px;
}

:deep(.el-radio-button__inner) {
  background: #fff;
  border: 1px solid #eaeaea;
  color: #2c3e50;
  border-radius: 6px;
  margin: 0 4px;
  transition: all 0.3s ease;
}

:deep(.el-radio-button__inner:hover) {
  background: #f8f9fa;
  border-color: #dcdfe6;
}

:deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  background: #2c3e50;
  border-color: #2c3e50;
  box-shadow: none;
}

.product-card {
  background: #fff;
  border: 1px solid #eaeaea;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.product-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-color: #dcdfe6;
}

.product-item {
  display: flex;
  gap: 24px;
  padding: 20px;
}

.product-image-container {
  position: relative;
  width: 160px;
  height: 160px;
  border-radius: 8px;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-item:hover .product-image {
  transform: scale(1.05);
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 4px 0;
}

.product-name {
  font-size: 18px;
  margin: 0 0 12px 0;
  color: #2c3e50;
  font-weight: 600;
}

.product-desc {
  margin: 12px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.product-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
}

.price {
  color: #2c3e50;
  font-size: 20px;
  font-weight: 600;
}

.sales {
  color: #909399;
  font-size: 13px;
  background: #f8f9fa;
  padding: 4px 12px;
  border-radius: 4px;
}

.product-actions {
  margin-top: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-btn {
  flex: 1;
  padding: 8px 16px;
  font-size: 14px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  transition: all 0.3s ease;
  border-radius: 6px;
}

.add-to-cart-btn {
  background: #2c3e50;
  color: #fff;
}

.add-to-cart-btn:hover {
  background: #34495e;
}

.favorite-btn {
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
}

.favorite-btn:hover {
  background: #f8f9fa;
  border-color: #c0c4cc;
}

.favorite-btn.is-favorite {
  background: #fff;
  border: 1px solid #e6a23c;
  color: #e6a23c;
}

.favorite-btn.is-favorite:hover {
  background: #fdf6ec;
}

:deep(.el-pagination) {
  margin-top: 32px;
  justify-content: center;
}

:deep(.el-pagination button),
:deep(.el-pagination .el-pager li) {
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  border-radius: 4px;
  margin: 0 4px;
  transition: all 0.3s ease;
}

:deep(.el-pagination button:hover),
:deep(.el-pagination .el-pager li:hover) {
  color: #2c3e50;
  border-color: #c0c4cc;
}

:deep(.el-pagination .el-pager li.active) {
  background: #2c3e50;
  border-color: #2c3e50;
  color: #fff;
}

/* 响应式设计优化 */
@media (max-width: 1200px) {
  .market-content {
    margin: 30px 20px;
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
    padding: 0 16px;
  }

  .search-bar {
    width: 100%;
    max-width: none;
    margin: 16px 0;
  }

  .market-content {
    flex-direction: column;
    padding: 16px;
  }

  .category-sidebar {
    width: 100%;
  }

  .product-item {
    flex-direction: column;
  }

  .product-image-container {
    width: 100%;
    height: 200px;
  }
}

/* 滚动条样式 */
:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}

:deep(.el-scrollbar__bar.is-vertical) {
  right: 0;
  width: 4px;
}

:deep(.el-scrollbar__thumb) {
  background: #dcdfe6;
  border-radius: 2px;
}

:deep(.el-scrollbar__thumb:hover) {
  background: #c0c4cc;
}

/* 高亮动画 */
.highlight-product {
  animation: highlight 1.5s ease-in-out;
}

@keyframes highlight {
  0% {
    box-shadow: 0 0 0 0 rgba(44, 62, 80, 0.1);
  }
  50% {
    box-shadow: 0 0 0 10px rgba(44, 62, 80, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(44, 62, 80, 0);
  }
}

.cart-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.empty-cart {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-items {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 10px;
}

.item-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.item-details h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.item-price {
  color: #f56c6c;
  font-weight: bold;
  margin: 0;
}

.item-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.cart-footer {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  background: #fff;
}

.cart-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  font-size: 18px;
}

.total-price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
}

.cart-actions {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-drawer__body) {
  padding: 0;
  height: calc(100% - 60px);
  overflow: hidden;
}

.cart-icon {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 20px;
  background: linear-gradient(45deg, rgba(64, 158, 255, 0.1), rgba(54, 207, 201, 0.1));
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.cart-icon::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: width 0.3s ease, height 0.3s ease;
}

.cart-icon:hover::after {
  width: 200%;
  height: 200%;
}

.cart-icon:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.cart-icon:active {
  transform: translateY(0);
}

.cart-icon .el-icon {
  font-size: 20px;
  color: #409EFF;
}

.cart-text {
  font-size: 14px;
  color: #409EFF;
  font-weight: 500;
}

.cart-badge :deep(.el-badge__content) {
  background: linear-gradient(45deg, #409EFF, #36cfc9);
  border: none;
  transition: transform 0.3s ease;
}

.cart-badge:hover :deep(.el-badge__content) {
  transform: scale(1.1);
}

/* 商家对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog__body) {
  padding: 20px 30px;
}

:deep(.el-form-item.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
}

:deep(.el-select) {
  width: 100%;
}

.favorites-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.empty-favorites {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.favorite-items {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.favorite-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 10px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.favorite-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.favorite-item .item-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.favorite-item .item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.favorite-item .item-details h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.favorite-item .item-price {
  color: #f56c6c;
  font-weight: bold;
  margin: 0;
}

.favorite-item .item-actions {
  display: flex;
  gap: 10px;
}

.order-confirm-content {
  padding: 20px;
}

.user-info-section,
.address-section,
.order-items,
.order-total,
.payment-method {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.user-info-section h3,
.address-section h3,
.order-items h3,
.order-total h3,
.payment-method h3 {
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.order-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
}

.order-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.item-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border-radius: 4px;
  object-fit: cover;
}

.item-info {
  flex: 1;
}

.item-info h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #303133;
}

.item-info p {
  margin: 5px 0;
  color: #606266;
}

.grand-total {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
}

:deep(.el-radio-group) {
  display: flex;
  gap: 20px;
}

:deep(.el-radio) {
  margin-right: 0;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  border-bottom: 1px solid #ebeef5;
}

.delete-btn {
  padding: 8px;
  margin-left: 8px;
}

.delete-btn .el-icon {
  font-size: 16px;
}

.cart-item {
  position: relative;
  transition: all 0.3s ease;
}

.cart-item:hover {
  background-color: #f5f7fa;
}

.item-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.item-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.item-details {
  flex: 1;
}

.item-details h4 {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #303133;
}

.item-price {
  color: #f56c6c;
  font-weight: bold;
  margin: 0;
}

/* 悬浮购物车样式 */
.floating-cart {
  position: fixed !important;
  right: 0;
  top: 0;
  height: 100vh;
  z-index: 2000;
  transition: transform 0.3s ease-in-out;
}

:deep(.el-drawer) {
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background: #fff;
}

:deep(.el-drawer__body) {
  padding: 0;
  height: calc(100% - 60px);
  overflow: hidden;
}

/* 悬浮购物车图标样式 */
.floating-cart-icon {
  position: fixed;
  right: 30px;
  bottom: 30px;
  width: 70px;
  height: 70px;
  background: linear-gradient(45deg, #409EFF, #36cfc9);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  z-index: 1000;
  padding: 10px;
}

.floating-cart-icon:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.cart-icon-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-body {
  position: relative;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-wheels {
  position: absolute;
  bottom: -8px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  padding: 0 5px;
}

.wheel {
  width: 12px;
  height: 12px;
  background: #fff;
  border-radius: 50%;
  box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.2);
}

.cart-handle {
  position: absolute;
  top: -12px;
  left: 50%;
  transform: translateX(-50%);
  width: 24px;
  height: 8px;
  background: #fff;
  border-radius: 4px 4px 0 0;
}

.floating-cart-icon .cart-icon {
  font-size: 28px;
  color: #fff;
  position: relative;
  z-index: 2;
}

.cart-tooltip {
  position: absolute;
  right: 90px;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
}

.floating-cart-icon:hover .cart-tooltip {
  opacity: 1;
}

.cart-badge :deep(.el-badge__content) {
  background: #fff;
  color: #409EFF;
  border: none;
  font-weight: bold;
  transform: scale(0.8);
  top: 5px;
  right: 5px;
}

/* 添加购物车动画 */
@keyframes addToCart {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.8;
  }
  100% {
    transform: scale(0.1);
    opacity: 0;
  }
}

.add-to-cart-animation {
  animation: addToCart 0.8s cubic-bezier(0.2, 0.5, 0.3, 1) forwards;
}

/* 购物车抽屉样式优化 */
.floating-cart {
  position: fixed !important;
  right: 0;
  top: 0;
  height: 100vh;
  z-index: 2000;
  transition: transform 0.3s ease-in-out;
}

:deep(.el-drawer) {
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background: #fff;
}

:deep(.el-drawer__body) {
  padding: 0;
  height: calc(100% - 60px);
  overflow: hidden;
}

/* 购物车内容区域样式优化 */
.cart-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.cart-items {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #fff;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 10px;
  background: #fff;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.cart-item:hover {
  transform: translateX(-5px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.cart-footer {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  background: #fff;
  position: sticky;
  bottom: 0;
  z-index: 1;
}

/* 添加购物车按钮动画 */
.add-to-cart-btn {
  position: relative;
  overflow: hidden;
}

.add-to-cart-btn::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: width 0.3s ease, height 0.3s ease;
}

.add-to-cart-btn:hover::after {
  width: 200%;
  height: 200%;
}
</style>
